/**
 * Created by Myron on 2015/9/10.
 */
var async = require('async');
var config = require('../config.js');
var signDayM = require('../models/signday.js');

module.exports = {
    //点击购物车按钮进入购物车
    index: function (req, res) {
        var uid = req.AV.user.id;
        //console.log(uid);
        //console.log(global.initData.signGifts);
        res.render('activity/signday1', {title: '每日签到'});
    },
    //进入页面获取数据
    getSignDayValueAjax:function(req, res){
        var uid = req.AV.user.id;
        async.waterfall([
            function(callback){
               //获取用户积分
                signDayM.get_UserInfo(uid).then(function(data){
                    callback(null, data.get('point'));
                }).catch(function(){
                    callback(null, 0)
                });
            },
            function(point,callback){
                //获取用户积分
                signDayM.getUserInfo(uid).then(function(data){
                    callback(null, point,data.get('firstSignDate'));
                }).catch(function(){
                    callback(null, 0)
                });
            },
            function(point,firstSignDate, callback) {
                var lastSignDate = new Date(new Date(firstSignDate).getTime()+365*24*60*60*1000);
                signDayM.getSignDayValue(uid).then(function(result){
                    callback(null,{code:result.code,MonthSignDay:result.MonthSignDay,AllSignDay:result.AllSignDay,AllSignDays:result.AllSignDays,SignState:result.SignState,GiftArray:result.GiftArray ,point:point,firstSignDate:firstSignDate,lastSignDate:lastSignDate});
                }).catch(function(result){
                    callback(null,{code:result.code,MonthSignDay:result.MonthSignDay,AllSignDay:result.AllSignDay,AllSignDays:result.AllSignDays,SignState:result.SignState,GiftArray:result.GiftArray ,point:point,firstSignDate:firstSignDate,lastSignDate:lastSignDate});
                });
            }
        ], function (err, result) {
            res.json(result);
        });
    },
    getRules:function(req, res){
        signDayM.getSignDayRules().then(function(result){
            res.json({supply:result,sign:global.initData.signGifts});
        });
    },
    //获取签到历史数据
    getSignDayDetailAjax:function (req, res) {
        var month = req.query.Month;
        var year = req.query.Year;
        var uid = req.AV.user.id;
        signDayM.getSignDayDetail(uid,year,month).then(function(result){
            res.json(result);
        });
    },
    //签到操作接口
    setSignDayActionAjax:function (req, res) {
        var uid = req.AV.user.id;
        //console.log('签到');
        async.waterfall([
            function(callback){
                signDayM.setSignDayAction(uid,new Date()).then(function(result){
                    //console.log("签到成功");
                    callback(null, {code:0,results:result});
                }).catch(function(result){
                    callback(null, {code:0,results:result});
                });
            },
            function(signSuccess,callback){
                if(signSuccess.code === 0){
                    signDayM.givePoint(uid,10).then(function(res){
                        callback(null,signSuccess);
                    });
                }
            },
            function(signSuccess,callback){
                //获取当前累计签到天数
                signDayM.getAllSignDays(uid).then(function(res){
                    //console.log("获取累计签到天数成功");
                    if(res){
                        callback(null, res.get('AllSignDays'));
                    }else{
                        callback(null, 0);
                    }
                }).catch(function(){
                    callback(null, 0);
                });
            },
            function(allsigndays,callback){
                //获取奖品等级
                signDayM.getGiftLevel(allsigndays).then(function(res){
                    //console.log("获取等级成功");
                    if(res.code === 0){
                        callback(null,{code:0,hasGift:1,level:res.level,AllSignDays:allsigndays});
                    }else{
                        callback(null,{code:0,hasGift:0,level:res.level,AllSignDays:allsigndays});
                    }
                });
            }
        ],function(err,results){
            if(err){
                //console.log(err);
                res.json(err);
            }else{
                res.json(results);
            }
        });
    },
    //领取奖品
    getGift:function(req,res){
        var level=req.query.level;
        //console.log('签到礼物等级：'+level);
        var uid = req.AV.user.id;
        var action = global.initData.signGifts[level].action;
        //console.log(action);
        //var action = global.initData.signGift.level.action ;
        async.auto({
            giveGift:function(callback){
                if(parseInt(action.limitMoney)!=-1){
                    //满减，获取cutMoney，执行满减方法
                    var limitMoney = parseInt(action.limitMoney) ;
                    var cutMoney = parseInt(action.cutMoney);
                    signDayM.giveMJ(uid,limitMoney,cutMoney).then(function(data){
                        callback(null, {code:0,msg:data.msg});
                    }).catch(function(err){
                        callback(null, {code:1,msg:""});
                    });
                }else if(parseInt(action.realMoney) != -1){
                    var realMoney = parseInt(action.realMoney);
                    //执行优惠劵
                    signDayM.giveCoupons(uid,realMoney).then(function(data){
                        callback(null, {code:0,msg:data.msg});
                    }).catch(function(err){
                        callback(null, {code:1,msg:""});
                    });
                }else if(parseInt(action.point) != -1){
                    var point = parseInt(action.point);
                    //执行发放积分
                    signDayM.givePoint(uid,point).then(function(data){
                        callback(null, {code:0,msg:data.msg});
                    }).catch(function(err){
                        callback(null, {code:1,msg:""});
                    });
                }else if(parseInt(action.gifts) != -1){
                    //执行发放礼品卷
                    signDayM.giveGiftToCart(uid,level).then(function(data){
                        callback(null, {code:0,msg:data.msg});
                    }).catch(function(err){
                        callback(null, {code:1,msg:""});
                    });
                }else if(parseInt(action.cash) != -1){
                    var cash = parseInt(action.cash);
                    //执行发放现金
                    signDayM.giveCash(uid,cash).then(function(data){
                        callback(null, {code:0,msg:data.msg});
                    }).catch(function(err){
                        callback(null, {code:1,msg:""});
                    });
                }else{
                    //其他特殊情况
                    callback(null, {code:0,msg:data.msg});
                }
            },
            updateGiveFlow:['giveGift',function(callback,results){
                var isReceived = 0 ;
                if(results.giveGift.code === 0){
                    isReceived = 1 ;
                }
                signDayM.updateGive(uid,level,isReceived).then(function(data){
                    //console.log('更新礼物流水表成功');
                    callback(null, data);
                })
            }]
        },function(err,results){
            if(err){
                //console.log(err)
                res.json(err);
            }else{
                res.json(results.updateGiveFlow);
            }
        });
    },
    getLevelOfBQ:function(req,res){
        var date=req.query.date;
        var uid = req.AV.user.id;
        signDayM.getLevelOfBQ(uid,date).then(function(data){
            //返回一个point
            res.json(data);
        });
    },
    cutPointOfBQ:function(req,res){
        var point=req.query.point;
        var uid = req.AV.user.id;
        signDayM.cutPointOfBQ(uid,point).then(function(data){
            //返回一个point
            res.json(data);
        });
    },
    signDaySupply:function(req,res){
        var uid = req.AV.user.id;
        var date = req.query.date;
        var point = req.query.point ;
        async.auto({
            //获取用户信息
            getUserInfo:function(callback){
                //console.log('success========cutPoint======');
                signDayM.getUserInfo(uid).then(function(uInfo){
                    if(uInfo){
                        callback(null, {code:0,userInfo:uInfo});
                    }else{
                        callback({code:-1,msg:'还没有签到过，不能补签'})
                    }
                }).catch(function(){
                    callback({code:-1,msg:'网络故障了，稍后再试'})
                });
            },
            //判断是日期是否在同一个周期内
            isInOneSize:['getUserInfo',function(callback,results){
                if(results.getUserInfo.code === 0){
                    var days = Math.floor((new Date(new Date(date).toDateString()) - new Date(results.getUserInfo.userInfo.get('firstSignDate').toDateString()))/(24*3600*1000));
                    if(days<=365 && days>=0){
                        callback(null);
                    }else{
                        return callback({code:100,msg:'不再同一个周期内，不能补签哦'+days});
                    }
                }else{
                    return callback({code:100,msg:'没有获取到用户信息'});
                }
            }],
            //开始签到
            signDayAction:['isInOneSize',function(callback){
                //console.log('success========signDayAction======');
                signDayM.setSignDayActionSupply(uid,new Date(date)).then(function(data){
                    if(data.code===0){
                        callback(null, {code:0});
                    }else{
                        callback(null, {code:1});
                    }
                }).catch(function(err){
                    return callback(err);
                });
            }],
            cutPoint:['signDayAction',function(callback,results){
                //console.log('success=======signDayAction=======');
                if(results.signDayAction.code === 0){
                    signDayM.cutPointOfBQ(date,uid,point).then(function(data){
                        if(data.code === 0){
                            callback(null, {code:0});
                        }else{
                            callback(null, {code:1});
                        }
                    }).catch(function(err){
                        return callback({code:100,msg:'扣减积分出错了1'});
                    });
                }else{
                    return callback({code:100,msg:'扣减积分出错了2'});
                }
            }],
            givePoint:['cutPoint',function(callback,results){
                if(results.signDayAction.code === 0 &&　results.cutPoint.code === 0){
                    signDayM.givePoint(uid,10).then(function(res){
                        callback(null)
                    });
                }
            }],
            getGiftsLevel:['givePoint','getUserInfo',function(callback,results){
                //console.log('success========getUserInfo======');
                if(results.getUserInfo.code === 0){
                    signDayM.getGiftLevel(parseInt(results.getUserInfo.userInfo.get('AllSignDays'))+1).then(function(level){
                        //console.log(level.level);
                        callback(null,level.level);
                    }).catch(function(err){

                    });
                }
            }],
            //判断是否满足发放礼物要求
            canGiveGift:['getGiftsLevel',function(callback,results){
                if(results.getGiftsLevel === 0){
                    //不满足要求
                    callback(null, {code:1,level:0})
                }else{
                    //满足要求
                    //判断是否发放过礼物
                    signDayM.isRecievedGifts(uid,results.getGiftsLevel).then(function(data){
                        if(data.code === 2){
                            //未领取过,可以发放礼物
                            callback(null, {code:0,level:results.getGiftsLevel});
                        }else{
                            //已领取
                            callback(null, {code:1});
                        }
                    });
                }
            }]
        },function(err,results){
            if(err){
                res.json(err);
            }else{
                //console.log('success==============');
                res.json(results.canGiveGift);
            }
        });
        //首先判断这一天是否签到
        //其次判断签到是否成功
        //再判断积分是否扣减成功
        //最后判断礼品是否满足规则，并且是否领取过，如果领取过就不发放，没有领取过就发放一遍
    },
    //判断礼品是否领取完成
    isSigndayTody:function(req,res){
        var uid = req.AV.user.id;
        //res.json(uid);
        signDayM.getSignDayValue(uid).then(function(result){
            if(result.code == 1003){
                //首次签到
                res.json({code:0,SignState:0,AllSignDays:0});
            }else{
                res.json({code:result.code,SignState:result.SignState,AllSignDays:result.AllSignDays});
            }
        }).catch(function(result){
            if(result.code == 1003){
                //首次签到
                res.json({code:0,SignState:0,AllSignDays:0});
            }else{
                res.json({code:result.code,SignState:result.SignState,AllSignDays:result.AllSignDays});
            }
        });
    }
}